<template>
  <div>
    <!-- 面包屑 -->
    <breadcrumb
      :breadcrumbArr="jsList.breadcrumbArr"
      :breadcrumbLastItem="breadcrumbLastItem"
      :state="state"
      @handleBack="handleBack"
    />
    <div v-if="isTrue" class="ccui-app-container-detail">
      <div class="ccui-app-container-detail-body">
        <el-tabs v-model="activeName" class="el-tabs__customize">
          <el-tab-pane label="基本信息" name="first">
            <baseInfo ref="baseInfo" :detail="detailInfo" />
          </el-tab-pane>

          <el-tab-pane label="财务信息" name="second">
            <financeInfo ref="financial" :detail="detailInfo.pcFinance || []" />
          </el-tab-pane>

          <el-tab-pane label="采购清单" name="third">
            <oneLineTable
              ref="purchaseList"
              showSummary
              :summaryArr="summaryArr"
              :tableTheadOptions="baseJsObj.purchaseTableThead"
              :oneLineTableData="detailInfo.smpConcMatLessList"
            />
          </el-tab-pane>

          <el-tab-pane label="使用范围" name="fourth">
            <oneLineTable
              ref="useRange"
              :tableTheadOptions="baseJsObj.useRangeTableThead"
              :oneLineTableData="detailInfo.smpUsableRange"
            />
          </el-tab-pane>

          <el-tab-pane label="付款方式" name="fifth">
            <paymentMode ref="paymentMode" :detail="detailInfo" />
          </el-tab-pane>

          <el-tab-pane label="合同附件" name="sixth">
            <contractAnnex
              ref="contractAnnex"
              v-model="uploadList"
              :state="state"
              :uploadBusinessType="3"
            />
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <!--  按钮  -->
    <el-bottom-guide>
      <ul class="ccui-bottom-button">
        <li>
          <el-button
            type="bottom"
            icon="icon-ccui-save"
            @click="submitHandle(0)"
            >保存并校验</el-button
          >
        </li>
        <li>
          <el-button
            type="bottom"
            icon="icon-ccui-cancel"
            @click="submitHandle(1)"
            >保存并提交</el-button
          >
        </li>
        <li>
          <el-button type="bottom" icon="icon-ccui-return" @click="handleBack"
            >返回</el-button
          >
        </li>
      </ul>
    </el-bottom-guide>
  </div>
</template>

<script>
import baseInfo from "./baseInfo";
import { proxyDateFormat } from "@/basa/utils";
import publicComponent from "@/basa/components/public";
import contractComponent from "@/app/contractManagement/components";
import jsList from "../js";
import baseJsObj from "@/app/contractManagement/equipmentContract/contractDraft/js";
import Mixin from "../mixins";
import {
  saveEqTakeEffect,
  editEqTakeEffect,
  getSmpEquipmentTakeEffectById
} from "../api";
export default {
  mixins: [Mixin],
  props: {
    state: {
      type: String,
      default: ""
    }
  },
  components: {
    baseInfo,
    financeInfo: contractComponent.detailFinanceInfo,
    paymentMode: contractComponent.detailPaymentMode,
    breadcrumb: publicComponent.breadcrumb,
    oneLineTable: publicComponent.oneLineTable,
    contractAnnex: contractComponent.takeEffectUploadInfo
  },
  data() {
    return {
      jsList,
      baseJsObj,
      breadcrumbLastItem: "合同生效",
      isTrue: false,
      detailInfo: {},
      activeName: "first",
      summaryArr: [
        "currentNum",
        "currentChangeAmtExcludeTax",
        "currentChangeAmtIncludeTax"
      ],
      uploadList: [],
      filterUploadList: [],
      concFileIds: [],
      lastFileSn: 0
    };
  },
  created() {
    // this.init();
  },
  activated() {
    this.init();
  },
  deactivated() {
    this.nextIsTrue();
  },
  methods: {
    init() {
      this.getSmpEquipmentTakeEffectById();
    },

    // 保存 提交
    async submitHandle(operType) {
      try {
        const { enabledDate, formalContractCode, id, version } =
          await this.$refs.baseInfo.handleSubmit();

        // 附件上传
        const fileReqBOS = this.uploadList
          .filter(_ => _.businessSonType === "2" && _.addFlag)
          .map((n, i) => ({
            sn: this.lastFileSn + i + 1,
            createTime: n.createTime,
            fileDesc: n.fileDesc,
            fileInfoId: n.uploadId || n.fileInfoId
          }));

        if (!fileReqBOS.length) {
          this.activeName = "sixth";
          this.$showErrorMessage("合同生效附件未填写，请上传后报存！");
          return;
        }

        // 组合数据
        let data = {
          operType,
          enabledDate,
          concId: this.$route.query.id,
          version,
          formalContractCode,
          fileReqBOS // 合同附件
        };
        if (this.state === "edit") data = { ...data, id };

        (this.state === "create" ? saveEqTakeEffect : editEqTakeEffect)(
          data
        ).then(res => {
          const { code, message } = res.data;
          if (code === "0") {
            this.$message.success(message);
            this.handleBack();
          }
        });
      } catch (error) {
        this.activeName = error;
        if (["first"].includes(error)) {
          this.$nextTick(() => {
            const errorFormEl = document.body.querySelector(".is-error");
            const errorText = errorFormEl.firstChild.innerText;
            const messageText = errorText.substring(
              0,
              errorText.lastIndexOf("：")
            );
            this.$showErrorMessage(`${messageText}未填写，请编辑后保存`);
            if (errorFormEl) {
              errorFormEl.scrollIntoView({
                behavior: "smooth", // 平滑过渡
                block: "start" // 上边框与视窗顶部平齐。默认值
              });
            }
          });
        }
      }
    },
    handleBack() {
      this.$router.go(-1);
    },

    // 获取详情
    getSmpEquipmentTakeEffectById() {
      const { id, recordId } = this.$route.query;
      let data = {
        concId: id,
        takeEffectId: recordId || "",
        isShowWorkflow: 1
      };
      if (this.state === "edit") data = { ...data, isChange: 1 };

      getSmpEquipmentTakeEffectById(data)
        .then(res => {
          const {
            data: { data }
          } = res;

          // 时间处理
          data.smpPcConc.compileDateStr = data.smpPcConc.compileDate
            ? proxyDateFormat(data.smpPcConc.compileDate)
            : "";
          data.smpUsableRange = data.smpUsableRange.map(n => ({
            ...n,
            operationTimeStr: n.operationTime
              ? proxyDateFormat(n.operationTime)
              : ""
          }));

          // 是否浮动合同价格
          data.smpPcConc.isFloatContractPrice = baseJsObj.whetherList.find(
            _ => _.dicKey === data.smpPcConc.isFloatContractPrice
          ).dicValue;

          // 是否海外采购
          data.smpPcConc.isOverseas = baseJsObj.isOverseasList.find(
            _ => _.value === data.smpPcConc.isOverseas
          ).label;

          // 多税率
          data.smpPcConc.multiRateCode = baseJsObj.whetherList.find(
            _ => _.dicKey === data.smpPcConc.multiRateCode
          ).dicValue;

          // 基础信息金额
          data.smpPcConc = {
            ...data.smpPcConc,
            initTotalContractPriceIncludeTax:
              data.smpPcConc.initTotalContractPriceIncludeTax !== null
                ? data.smpPcConc.initTotalContractPriceIncludeTax.toFixed(2)
                : "",
            initTotalConractPriceExcludeTax:
              data.smpPcConc.initTotalConractPriceExcludeTax !== null
                ? data.smpPcConc.initTotalConractPriceExcludeTax.toFixed(2)
                : ""
          };

          // 清单设置地区
          if (data.smpConcMatLessList.length) {
            data.smpConcMatLessList = data.smpConcMatLessList.map(n => ({
              ...n,
              deliveryTime: n.deliveryTime
                ? proxyDateFormat(n.deliveryTime)
                : "",
              currentNum: n.currentNum !== null ? n.currentNum.toFixed(3) : "",
              currentUnitPriceExcludeTax:
                n.currentUnitPriceExcludeTax !== null
                  ? n.currentUnitPriceExcludeTax.toFixed(2)
                  : "",
              currentChangeAmtExcludeTax:
                n.currentChangeAmtExcludeTax !== null
                  ? n.currentChangeAmtExcludeTax.toFixed(2)
                  : "",
              currentUnitPriceIncludeTax:
                n.currentUnitPriceIncludeTax !== null
                  ? n.currentUnitPriceIncludeTax.toFixed(2)
                  : "",
              currentChangeAmtIncludeTax:
                n.currentChangeAmtIncludeTax !== null
                  ? n.currentChangeAmtIncludeTax.toFixed(2)
                  : "",
              rate: n.rate !== null ? n.rate.toFixed(2) : "",
              address:
                (n.deliveryAreaName || "") +
                (n.provinceName || "") +
                (n.cityName || "") +
                (n.countyName || "") +
                (n.deliveryPoints || "") // 交货地点
            }));
          }

          if (data.smpEnabledRecordBO) {
            data.smpEnabledRecordBO.enabledDate = data.smpEnabledRecordBO
              .enabledDate
              ? proxyDateFormat(data.smpEnabledRecordBO.enabledDate)
              : "";
          }
          // 赋值
          this.concFileIds = data.concFiles.map(
            _ => _.uploadId || _.fileInfoId
          );

          // 过滤附件
          this.uploadList = data.concFiles.filter(_ =>
            ["1", "2", "3"].includes(_.businessSonType)
          );

          this.lastFileSn = data.concFiles.length
            ? data.concFiles.slice(-1)[0].sn
            : 0;

          if (this.state === "edit") delete data.smpEnabledRecordBO.version;
          data.smpPcConc = Object.assign(
            data.smpPcConc,
            data.pcFinance[0] || {},
            data.smpEnabledRecordBO || {}
          );
          this.detailInfo = Object.assign(data, {
            state: "detail"
          });
          // this.breadcrumbLastItem = data.smpPcConc.contractName;
          if (this.state == "edit") {
            this.breadcrumbLastItem = data.smpPcConc.contractName;
          }
          this.isTrue = true;
        })
        .catch(e => {});
    }
  }
};
</script>
